package com.example.handsets8app.View.TuLou1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.handsets8app.Base.BaseConfig;
import com.example.handsets8app.R;
import com.example.handsets8app.Utils.SPUtil;
import com.example.handsets8app.Utils.SelfToastUtil;
import com.example.handsets8app.Utils.StringUtil;
import com.example.handsets8app.View.MainActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginTulouActivity extends AppCompatActivity {

    private EditText etIpName;
    private EditText etAccount;
    private EditText etPw;
    private String Url;
    private String gateNo;
    private Button btBind;
    private LinearLayout llSetting;
    private boolean isShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_tulou);

        btBind = findViewById(R.id.bt_bind);
        etIpName = findViewById(R.id.ipname);
        etAccount = findViewById(R.id.account);
        etPw = findViewById(R.id.pwd);
        llSetting = findViewById(R.id.ll_setting);

        llSetting.setVisibility(View.INVISIBLE);

        Url = (String) SPUtil.get(LoginTulouActivity.this, BaseConfig.TULOU_IP, "");
        gateNo = (String) SPUtil.get(LoginTulouActivity.this, BaseConfig.TULOU_GATENO, "");
        etIpName.setText(Url);
        etAccount.setText((String) SPUtil.get(LoginTulouActivity.this, BaseConfig.TULOU_ACCOUNT, ""));
        etPw.setText((String) SPUtil.get(LoginTulouActivity.this, BaseConfig.TULOU_PW, ""));


        if (!TextUtils.isEmpty(gateNo)) {
            //如果不为空
            btBind.setText("已绑定闸机（点击取消绑定）");
        } else {
            btBind.setText("未绑定闸机(登录绑定闸机)");
        }

        btBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpURLRelese();
            }
        });

        //判断是否需要登入  如果有用户名和密码不为空就去的登入一次
//        if (!StringUtil.isNullOrEmpty(etAccount.getText().toString()) && !StringUtil.isNullOrEmpty(etPw.getText().toString())) {
//            goToLogin();
//        }

    }

    private void HttpURLRelese() {
        new Thread() {
            public void run() {
                sendRelese();
            }
        }.start();
    }

    private boolean sendRelese() {

        try {
            String sendUrl = Url + "checkTicketInterface/gateReleseBound.do";

            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", etAccount.getText().toString());
            map.put("password", etPw.getText().toString());
            map.put("gateNo", gateNo);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

            String sendDate = "userName=" + etAccount.getText().toString() + "&password=" + etPw.getText().toString() + "&gateNo=" + gateNo + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            if (result.indexOf("<code>0</code>") > 0) {
                SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_GATENO, "");
                gateNo = "";
                btBind.setText("未绑定闸机(登录绑定闸机)");
//                HttpURL();
                showToast("取消绑定成功！");
            } else if (result.indexOf("<code>50002</code>") > 0) {
                SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_GATENO, "");
                gateNo = "";
                btBind.setText("未绑定闸机(登录绑定闸机)");
//                HttpURL();
                showToast("取消绑定成功！");
            } else {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }

        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SelfToastUtil.getInstance().show("已解绑闸机！");
                }
            });

            return false;
        }
        return true;


    }

    //非UI线程中显示Toast
    public void showToast(String msg) {
        Looper.prepare();//?
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }

    // 登入的点击事件
    public void BtnOnClick(View view) {
        goToLogin();
    }

    private void goToLogin() {
        Url = etIpName.getText().toString();
        if (StringUtil.isNullOrEmpty(Url)) {
            SelfToastUtil.getInstance().show("请输入IP地址");
            return;
        }

        if (StringUtil.isNullOrEmpty(etAccount.getText().toString())) {
            SelfToastUtil.getInstance().show("请输入用户名");
            return;
        }

        if (StringUtil.isNullOrEmpty(etPw.getText().toString())) {
            SelfToastUtil.getInstance().show("请输入密码");
            return;
        }

        SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_IP, Url);
        SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_ACCOUNT, etAccount.getText().toString());
        SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_PW, etPw.getText().toString());
        // 如果都通过了，那么就去登入

        if (gateNo == null || gateNo.equals("")) {
            HttpURL();
        } else {
            // 如果不为空，那么就直接进入检票
            Intent intent = new Intent(LoginTulouActivity.this, TuLouMainActivity.class);
            Bundle bundle = new Bundle();

            bundle.putString("url", Url);
            bundle.putString("myname", etAccount.getText().toString());
            bundle.putString("mypwd", etPw.getText().toString());
            bundle.putString("gateno", gateNo);

            intent.putExtras(bundle);
            startActivity(intent);

//            ShowDialog();
        }
    }

    private void HttpURL() {
        new Thread() {
            public void run() {
                send();
            }
        }.start();
    }

    private boolean send() {

        try {
            String sendUrl = Url + "checkTicketInterface/userLogin.do";

            //1E2147E55DEBE89F795C4BAE81C78890
            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", etAccount.getText().toString());
            map.put("password", etPw.getText().toString());
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

            SPUtil.put(LoginTulouActivity.this, BaseConfig.TULOU_SING, sign);

            String sendDate = "userName=" + etAccount.getText().toString() + "&password=" + etPw.getText().toString() + "&sign=" + sign;

            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            if (result.indexOf("<code>0</code>") > 0) {

                if (gateNo == null || gateNo.equals("")) {
                    Intent intent = new Intent(LoginTulouActivity.this, SelectGateActivity.class);

                    /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
                    intent.putExtra("url", Url);
                    intent.putExtra("myname", etAccount.getText().toString());
                    intent.putExtra("mypwd", etPw.getText().toString());
                    /*把bundle对象assign给Intent*/
                    startActivity(intent);
                } else {
                    //提示是否取消绑定
                    Intent intent = new Intent(LoginTulouActivity.this, TuLouMainActivity.class);
                    startActivity(intent);
                }
                finish();
            } else {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                SelfToastUtil.getInstance().show(msg);
            }
        } catch (Exception e) {
            SelfToastUtil.getInstance().show("请检查地址配置！");

            return false;
        }
        return true;
    }


    public String getxmlstr(String xml, String resultstr) {
        ByteArrayInputStream tInputStringStream = null;
        String returnstr = "";
        try {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        } catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(resultstr)) {
                            returnstr = parser.nextText();
                            System.out.println(returnstr);

                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return returnstr;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param sendUrl 发送请求的 URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            // 获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    /**
     * 生成签名结果
     *
     * @param sArray 要签名的数组
     * @param key    通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray, String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }


    // 退出的点击事件
    public void BtnOnClickcancle(View view) {
        //退出程序
        android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
    }

    public void bt_Show_Setting(View view) {
        //显示配置信息
        if (isShow) {
            llSetting.setVisibility(View.INVISIBLE);
            isShow = !isShow;
        }else {
            llSetting.setVisibility(View.VISIBLE);
            isShow = !isShow;
        }
    }
}
